package com.heba.fragment.message;

import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.heba.Cfg;
import com.heba.adapter.QuickAdapter;
import com.heba.bean.message.ItemMationObject;
import com.heba.bean.message.ItemMessageObject;
import com.heba.config.CommonConfig;
import com.heba.event.MessageEvent;
import com.heba.fragment.LazyFragment;
import com.heba.greenmulu.R;
import com.heba.greenmulu.diary.ItemDiaryDetailActivity;
import com.heba.greenmulu.message.ItemMessageChatDetailActivity;
import com.heba.helper.DateHelper;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.utils.GlideUtil;
import com.heba.view.RoundImageView;
import com.loopj.android.http.RequestParams;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 通訊錄訊息頁面
 * Created by jason on 2020/1/7.
 */
public class MessageMessagesFragment extends LazyFragment {

    private SmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private QuickAdapter recycleAdapter;

    private List<ItemMessageObject> list;
    private List<ItemMationObject> mationObjectList;

    private List<Object> allList;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void lazyLoad() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_message_messages, container, false);
        EventBus.getDefault().register(this);
        initView(view);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        refreshMessageListData();
    }

    /**
     * initView
     *
     * @param view
     */
    private void initView(View view) {
        refreshLayout = view.findViewById(R.id.refreshLayout);
        recyclerView = view.findViewById(R.id.recyclerView);
        mationObjectList = new ArrayList<>();
        allList = new ArrayList<>();
        list = new ArrayList<>();

        recycleAdapter = new QuickAdapter<Object>(allList) {
            @Override
            public int getLayoutId(int viewType) {
                if (viewType == 0){
                    return R.layout.recycle_alert_you_row;
                }else{
                    return R.layout.recycle_item_message_row;
                }
            }
            @Override
            public int getItemViewType(int position) {
                if (position<mationObjectList.size()) {
                    return 0;
                }
                else {
                    return 1;
                }
            }
            @Override
            public void convert(VH holder, Object data, int position) {
                if (position<mationObjectList.size()){
                    ItemMationObject obj = (ItemMationObject)data;
                    RoundImageView avatar = holder.getView(R.id.friend_avatar);
                    TextView contentTV = holder.getView(R.id.metion_text);
                    ImageView diaryImage = holder.getView(R.id.diary_image);
                    GlideUtil.loadImageWithDefaultPlaceHolder(getContext(),obj.getIcon(),avatar);
                    contentTV.setText(obj.getAccount()+" "+getResources().getString(R.string.mation_you));
                    GlideUtil.loadImageWithDefaultPlaceHolder(getContext(),obj.getImageUrl(),diaryImage);
                    holder.itemView.setOnClickListener(v -> {
                        readAlertMessage(obj);
                        Bundle bundle = new Bundle();
                        bundle.putString(CommonConfig.DIARY_ID,obj.getDiaryID());
                        openActivity(ItemDiaryDetailActivity.class,bundle);
                    });

                }else {
                    ItemMessageObject obj = (ItemMessageObject)data;
                    GlideUtil.loadImageWithPlaceHolderID(getActivity(), obj.getIcon(), holder.getView(R.id.iv_avatar), R.drawable.icon_head_portrait);
                    holder.setText(R.id.tv_name, obj.getAccount());
                    holder.setText(R.id.tv_time, DateHelper.transferDateString(getActivity(), obj.getTimeCreated()));
                    holder.getView(R.id.tv_nums).setVisibility(View.INVISIBLE);
                    holder.setText(R.id.tv_content, "");
                    //有未讀消息
                    if (obj.getIsView() != 1) {
                        holder.getView(R.id.tv_nums).setVisibility(View.VISIBLE);
                    }

                    //判断是发送消息还是收到消息
                    if (obj.getStatus() == 1) {
                        //发送消息
                        holder.setText(R.id.tv_content, String.format(getResources().getString(R.string.message_message_content1), obj.getAccount()));
                    } else {
                        //收到消息
                        holder.setText(R.id.tv_content, String.format(getResources().getString(R.string.message_message_content), obj.getAccount()));
                    }

                    /**
                     * 进入讯息详情页
                     */
                    holder.itemView.setOnClickListener(v -> {
                        Bundle bundle = new Bundle();
                        bundle.putString(CommonConfig.USER_NAME, obj.getAccount());
                        bundle.putString(CommonConfig.USER_ICON, obj.getIcon());
                        bundle.putString(CommonConfig.SEND_USER_ID, obj.getUserID());
                        bundle.putInt(CommonConfig.ACCOUNT_TYPE,obj.getAccountType());
                        openActivity(ItemMessageChatDetailActivity.class, bundle);
                    });
                }
            }
        };

        /**
         * 设置layoutManager布局
         */
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //设置Adapter
        recyclerView.setAdapter(recycleAdapter);

        //设置是否监听滚动到底部是触发自动刷新
        refreshLayout.setEnableAutoLoadMore(false);

        /**
         * 处理下拉刷新事件
         */
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            refreshMessageListData();
        });

        /**
         * 处理上拉加载事件
         */
        refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            Page++;
            isRefreshFromTop = false;
            getMessageListData();
        });
    }

    /**
     * 刷新數據
     */
    private void refreshMessageListData() {
        Page = 1;
        isRefreshFromTop = true;
        getMessageListData();
    }

    /**
     * 获取讯息列表数据
     */
    private void getMessageListData() {
        if (firstRefresh) {
            firstRefresh = false;
            progressDialog.show();
        }
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("p", Page);
        params.put("pp", PerPage);
        client.get(Cfg.BaseUrl + "/Notice/Message", params,
                new JSONHttpHelper.JSONHttpResponseHandler(getActivity()) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();


                        /**
                         * 下拉刷新处理
                         */
                        if (isRefreshFromTop) {
                            isRefreshFromTop = false;
                            refreshLayout.setNoMoreData(false);
                            list.clear();
                            mationObjectList.clear();
                            allList.clear();
                        }

                        try {
                            JSONArray array = new JSONObject(response.trim()).getJSONArray("Result");
                            if (array.length() > 0) {
                                allList.clear();
                                List<ItemMessageObject> objects = new Gson().fromJson(array.toString(), new TypeToken<List<ItemMessageObject>>() {
                                }.getType());
                                list.addAll(list.size(), objects);

                            } else {
                                //无数据
                                refreshLayout.finishLoadMoreWithNoMoreData();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        getMationData();
                        //刷新数据
                    }

                    public void Failure() {
                        super.Failure();
                        progressDialog.dismiss();
                        closeRefreshView(refreshLayout);
                    }

                });
    }

    private void readAlertMessage(ItemMationObject mationObject){
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("UserID",Cfg.UserID);
        params.put("ID",mationObject.getID());
        client.get(Cfg.BaseUrl + "/Notice/SetAMessageIsView", params,
                new JSONHttpHelper.JSONHttpResponseHandler(getActivity()) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        refreshMessageListData();
                    }

                    public void Failure() {
                        super.Failure();

                    }

                });

    }

    /**
     * 获取@列表数据
     */
    private void getMationData() {

        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);

        client.get(Cfg.BaseUrl + "/Notice/AMessage", params,
                new JSONHttpHelper.JSONHttpResponseHandler(getActivity()) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        progressDialog.dismiss();
                        closeRefreshView(refreshLayout);

                        /**
                         * 下拉刷新处理
                         */
                        if (isRefreshFromTop) {
                            isRefreshFromTop = false;
                            refreshLayout.setNoMoreData(false);
                            list.clear();
                            mationObjectList.clear();
                            allList.clear();
                        }

                        try {
                            JSONArray array = new JSONObject(response.trim()).getJSONArray("Result");
                            if (array.length() > 0) {
                                List<ItemMationObject> objects = new Gson().fromJson(array.toString(), new TypeToken<List<ItemMationObject>>() {
                                }.getType());
                                mationObjectList.addAll(mationObjectList.size(), objects);
                                allList.addAll(mationObjectList);
                                allList.addAll(list);
                            } else {
                                //无数据
                                allList.addAll(list);
                                refreshLayout.finishLoadMoreWithNoMoreData();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        //刷新数据
                        recycleAdapter.notifyDataSetChanged();
                    }

                    public void Failure() {
                        super.Failure();
                        progressDialog.dismiss();
                        closeRefreshView(refreshLayout);
                    }

                });
    }
    /**
     * 接收EventBus
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        /**
         * 更新列表數據
         */
        if (event.getEvent().equals(CommonConfig.EVENT_UPDATE_MESSAGE)) {
            refreshMessageListData();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //反註冊
        EventBus.getDefault().unregister(this);
    }

}
